<template>
  <el-dialog
    class="dialog-face"
    v-model="visible"
    width="80%"
    :show-close="false"
    style="--el-dialog-padding-primary: unset"
    @opened="onOpen"
    @close="onClose"
  >
    <template #header>
      <div class="header">考勤打卡</div>
    </template>
    <div class="section">
      <div class="section-left">
        <template v-if="detail?.face_image">
          <img
            class="avatar"
            :src="detail.face_image"
          />
        </template>
        <template v-else>
          <div
            class="avatar avatar-blue"
            style="display: flex; align-items: center; justify-content: center"
            :class="userType == 1 ? 'avatar-blue' : 'avatar-pink'"
          >
            <img :src="require(`@/assets/avatar0${userType}.png`)" />
          </div>
        </template>
        <div class="text">姓名：{{ detail?.name || "-" }}</div>
        <div class="text">{{ detail?.account_no }}</div>
        <div class="text status">
          {{ detail?.name ? "验证通过" : "识别中..." }}
        </div>
      </div>
      <div class="section-right">
        <div class="face-wrap">
          <div
            ref="faceRef"
            style="width: 100%; height: 100%"
          ></div>
        </div>
        <p>刷卡或人脸识别考勤打卡</p>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { computed, defineProps, defineEmits, ref, inject } from "vue";
import { ElMessage, ElNotification, ElDialog } from "element-plus";
import { attendance } from "@/api/apiData";
import { AesEncode } from "@/utils/crypto/crypto.js";
const { deviceDetail } = inject("global-stroe");
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  userType: {
    type: [String, Number], // 身份类型:1=学生,2=教师
  },
});
const emits = defineEmits(["update:modelValue", "close"]);
const visible = computed({
  get() {
    return props.modelValue;
  },
  set(newVal) {
    emits("update:modelValue", newVal);
  },
});
const detail = ref({});
const faceRef = ref();
const onOpen = () => {
  try {
    // console.log('androidClient',androidClient);
    //1、调用显示/隐藏人员识别区域
    showFaceReview();
    //2、在当前页面人员识别/刷卡接收相应数据
    window.addEventListener("message", getFaceMessage);
    // console.log("androidClient", androidClient);
  } catch (error) {
    /* ElNotification({
      title: "onMounted",
      message: error,
      position: "bottom-left",
    }); */
    console.error("onOpen", error);
  }
};

/**
 * 调用显示人员识别区域
 */
function showFaceReview() {
  try {
    /*
        显示人员识别区域方法
        androidClient.showCameraPreview(int left, int top, int width, int height, false, false);
        left:距屏幕左边距
        top:距屏幕上边距
        width:识别框宽度
        height:识别框高度
    */
    const rect = faceRef.value.getBoundingClientRect();
    // DOMRect对象包含以下属性（单位：像素）
    // console.log("元素上边距:", rect.top); // 元素顶部到视口顶部的距离
    // console.log("元素左边距:", rect.left); // 元素左侧到视口左侧的距离
    // console.log("元素右边距:", rect.right); // 元素右侧到视口左侧的距离
    // console.log("元素下边距:", rect.bottom); // 元素底部到视口顶部的距离
    // 额外属性
    // console.log("元素宽度:", rect.width); // 元素宽度（包含padding和border）
    // console.log("元素高度:", rect.height); // 元素高度（包含padding和border）

    const left = rect.left;
    const top = rect.top;
    const width = rect.width;
    const height = rect.height;
    // console.log("left", left);
    // console.log("top", top);
    // console.log("width", width);
    // console.log("height", height);
    androidClient.showCameraPreview(left, top, width, height, false, false);
    //隐藏人员识别区域方法
    //androidClient.hideCameraPreview();
  } catch (error) {
    console.log("showFaceReview");
  }
}

/**
 * 在当前页面人员识别/刷卡接收相应数据
 */
function getFaceMessage(ev) {
  /*  if (!ev?.data?.includes("webpack")) {
      console.log("punch", JSON.parse(ev.data));
    } */
  let RecvMessage = JSON.parse(ev.data);
  console.log('RecvMessage',RecvMessage);
  switch (RecvMessage.action) {
    case "PostCardInfo":
      // console.log("卡号：" + RecvMessage.CardNo);
      //弹出提示
      // androidClient.showText("卡号：" + RecvMessage.CardNo);
      break;
    case "PostFaceInfo":
      console.log("工号：" + RecvMessage.AccountNo);
      //弹出提示
      // androidClient.showText("工号：" + RecvMessage.AccountNo);
      punch(RecvMessage.AccountNo);
      break;
    default:
      break;
  }
}

const onClose = () => {
  detail.value = {};
  window.removeEventListener("message", getFaceMessage);
  console.log('removeEventListener');
  emits("close");
  try {
    androidClient && androidClient.hideCameraPreview();
  } catch (error) {
    console.error("onClose:", error);
  }
};

/**
 * 打卡
 */
function punch(account_no) {
  const room_id = deviceDetail.value?.room_id;
  let params = {
    room_id,
    user_type: props.userType,
    account_no: AesEncode(account_no),
  };
  attendance
    .punch(params)
    .then(({ code, data, msg }) => {
      if (code === 1) {
        detail.value = {
          ...data,
          account_no,
        };
        ElMessage.success({
          customClass: "custom-message",
          message: msg || "打卡成功！",
        });
      } else {
        // ElMessage.warning(msg);
        ElMessage.warning({
          customClass: "custom-message",
          message: msg,
        });
      }
    })
    .catch(() => {
      ElMessage.error("服务器报错，请稍后重试！");
    });
}
</script>

<style
  lang="less"
  scoped
>
.dialog-face {
  .header {
    width: 100%;
    height: 68px;
    line-height: 68px;

    background: linear-gradient(90deg, #56abf9 0%, #5686fc 100%);

    font-weight: 500;
    font-size: 32px;
    color: #ffffff;

    text-align: center;
  }
  .section {
    display: flex;
    align-items: center;
    padding: 34px 121px 58px 75px;
    &-left {
      padding-right: 97px;
      border-right: 1px solid #dcdcdc;
      .avatar {
        width: 331px;
        height: 391px;
        background: #cccccc;
        border-radius: 4px;
        &-blue {
          background: #d5e3ff;
        }

        &-pink {
          background: #ffd5d5;
        }
      }
      .text {
        font-size: 24px;
        color: #333333;
        margin-bottom: 16px;
        &:first-of-type {
          margin-top: 20px;
        }
      }
      .status {
        color: #00d146;
      }
    }
    &-right {
      /* 770px x 454px */
      margin-left: 132px;
      .face-wrap {
        width: 770px;
        height: 454px;
        padding: 4px;
        background: url("@/assets/face-bg.png") no-repeat center/100% 100%;
        box-sizing: border-box;
      }
      & > p {
        margin-top: 26px;
        text-align: center;
        font-size: 32px;
        color: #5688fc;
      }
    }
  }
}
</style>
<style lang="less">
.custom-message {
  padding: 20px;
  font-size: 40px;
  .el-message__content {
    font-size: inherit !important;
  }
}
</style>
